package com.ztom.offer.v2;

/**
 * 矩阵中的路径
 * <p>
 * https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
 *
 * @author ZhangTao
 */
public class Code10Exist {

    public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0
                || board[0] == null || board[0].length == 0
                || word == null) {
            return false;
        }
        int m = board.length;
        int n = board[0].length;
        char[] words = word.toCharArray();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (dfs(board, i, j, words, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, int i, int j, char[] words, int k) {
        // 越界
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
            return false;
        }
        // 不匹配
        if (board[i][j] != words[k]) {
            return false;
        }
        // 匹配到最后一个字符
        if (k == words.length - 1) {
            return true;
        }
        // 标记访问
        board[i][j] = '*';
        // 去上下左右尝试匹配
        boolean result = dfs(board, i, j + 1, words, k + 1)
                || dfs(board, i, j - 1, words, k + 1)
                || dfs(board, i - 1, j, words, k + 1)
                || dfs(board, i + 1, j, words, k + 1);

        // 恢复现场
        board[i][j] = words[k];
        return result;
    }


    public boolean exist1(char[][] board, String word) {
        if (board == null || board.length == 0
                || board[0] == null || board[0].length == 0
                || word == null) {
            return false;
        }
        int m = board.length;
        int n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (dfs1(board, visited, i, j, word, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs1(char[][] board, boolean[][] visited, int i, int j, String word, int k) {
        if (board[i][j] != word.charAt(k)) {
            return false;
        }
        // 匹配到最后一个字符
        if (k == word.length() - 1) {
            return true;
        }
        visited[i][j] = true;
        // 去上下左右尝试匹配
        int[][] dirs = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
        boolean result = false;
        for (int[] dir : dirs) {
            int ni = i + dir[0];
            int nj = j + dir[1];
            if (ni >= 0 && ni < board.length
                    && nj >= 0 && nj < board[0].length
                    && !visited[ni][nj]) {
                if (dfs1(board, visited, ni, nj, word, k + 1)) {
                    result = true;
                    break;
                }
            }
        }
        // 恢复现场
        visited[i][j] = false;
        return result;
    }
}
